package com.yanqu.road.server.manger.activity.cookboy;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.cookboy.CookBoyData;
import com.yanqu.road.entity.activity.cookboy.CookBoyFinishFood;
import com.yanqu.road.entity.activity.cookboy.CookBoyFood;
import com.yanqu.road.entity.activity.cookboy.MakeFoodRes;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.activity.eActivityCookBoyType;
import com.yanqu.road.entity.enums.eCookBoyFoodStatusType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogCookBoy1MakeFood;
import com.yanqu.road.entity.log.LogCookBoy1MatchFood;
import com.yanqu.road.entity.log.LogCookBoy1MergeFood;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.task.args.RelationActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.bussiness.player.UserCookBoyBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.cookboy.CookBoyProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.cookboy.CookBoyModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.RelationActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.PropertyHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CookBoy {

	private Logger logger = LogManager.getLogger(CookBoy.class.getName());

	private final Map<Long,Object> lockMap = new ConcurrentHashMap<>();

	private ActivityInfo activityInfo;

	//用户id 用户数据
	private Map<Long, CookBoyData> cookBoyDataMap = new ConcurrentHashMap<>();

	private List<CookBoyData> needAddCookBoyList = new ArrayList<>();

	private List<CookBoyData> needUpdateCookBoyList = new ArrayList<>();

	//正在发菜场景的人
	private Map<Long,List<Long>> sceneUserMap = new ConcurrentHashMap<>();

	public CookBoy(ActivityInfo acInfo){
		activityInfo = acInfo;
//		reload();
	}

	public void setActivityInfo(ActivityInfo activityInfo){
		this.activityInfo = activityInfo;
	}

	public Object getLock(long userId){
		synchronized (lockMap){
			if(!lockMap.containsKey(userId)){
				lockMap.put(userId,new Object());
			}
			return lockMap.get(userId);
		}
	}

	public boolean isSceneUser(long userId,long openBanquetUserId){
		for(Long inUserId : sceneUserMap.get(openBanquetUserId)){
			if(inUserId == userId){
				return true;
			}
		}
		return false;
	}

	public void recoverHp(long userId,long count){
		Object locker = getLock(userId);
		synchronized (locker){
			CookBoyData cookBoyData = cookBoyDataMap.get(userId);
			if(cookBoyData == null){
				logger.error("当家活动{},{}还没生成数据玩家就开始使用恢复体力道具了",activityInfo.getActivityId(),userId);
				return;
			}
			recoveryMakeFoodHp(cookBoyData);
			if (count <= 0) {
				return;
			}
			GoodsInfo goodsInfo = GoodsMgr.getGoodsById(CookBoyActivityMgr.getCookBoyHpItemId(activityInfo.getActivityId()));
			long recoverHp = goodsInfo.getParamList().get(0).longValue() * count;
			cookBoyData.setHp(cookBoyData.getHp() + (int)recoverHp);
			GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
			player.getModule(CookBoyModule.class).syncSelfTable(activityInfo.getActivityId());
		}
	}

	public int worship(long userId){
		Object locker = getLock(userId);
		synchronized (locker){
			CookBoyData cookBoyData = cookBoyDataMap.get(userId);
			if(cookBoyData.isWorship()){
				return GameErrorCode.E_COOK_BOY_FOOD_IS_WORSHIP;
			}
			GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
			if(gamePlayer != null){
				cookBoyData.setWorship(true);
				synchronized (needUpdateCookBoyList){
					if(!needUpdateCookBoyList.contains(cookBoyData)){
						needUpdateCookBoyList.add(cookBoyData);
					}
				}
				gamePlayer.getModule(CurrencyModule.class).addCurrency(CookBoyActivityMgr.getWorshipReward(activityInfo.getActivityId()),eLogMoneyType.CookBoy,eLogMoneyType.CrossCookBoyActivityWorship);
			}
		}
		return 0;
	}

	public void addSceneUser(long userId,long openBanquetUserId){
		if(!sceneUserMap.containsKey(openBanquetUserId)){
			sceneUserMap.put(openBanquetUserId,new ArrayList<>());
		}
		for(List<Long> userIdList : sceneUserMap.values()){
			userIdList.remove(userId);
		}
		sceneUserMap.get(openBanquetUserId).add(userId);
	}

	public void removeSceneUser(long userId,long openBanquetUserId){
		if(sceneUserMap.containsKey(openBanquetUserId)){
			sceneUserMap.get(openBanquetUserId).remove(userId);
		}
	}

	public List<Long> getSceneUser(long openBanquetUserId){
		if(sceneUserMap.containsKey(openBanquetUserId)){
			return new ArrayList<>(sceneUserMap.get(openBanquetUserId));
		}
		return  new ArrayList<>();
	}


	public CookBoyData getUserCookBoyData(GamePlayer player){
		if(!cookBoyDataMap.containsKey(player.getUserId())){
//			clearIntegral(player,CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId()));
			cookBoyDataMap.put(player.getUserId(),initCookBoy1(player.getUserId()));
		}else{
			reAddIntegral(player,CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId()));
		}
		return cookBoyDataMap.get(player.getUserId());
	}

	public Map<Long,CookBoyData> getWindUpUserCookBoyMap(List<Long> userIdList){
		Map<Long,CookBoyData> res = new ConcurrentHashMap<>();
		for(long userId : userIdList){
			if(cookBoyDataMap.containsKey(userId)){
				res.put(userId,cookBoyDataMap.get(userId));
			}
		}
		return res;
	}

	//比赛结束的每一场排名的奖励
	public void updateMatchOverFood(CookBoyProto.CrossCookBoyMatchOverRewardSyncMsg msg){
		for(CookBoyProto.CrossCookBoyMatchOverUserTempMsg temp : msg.getInfoListList()){
			Object locker = getLock(temp.getUserId());
			synchronized (locker){
				CookBoyData cookBoyData = cookBoyDataMap.get(temp.getUserId());
				UserInfo userInfo = UserMgr.getUserInfo(temp.getUserId());
				RelationActivityMgr.conditionNotify(activityInfo.getActivityId(),temp.getUserId(), eGamePlayerEventType.CookBoy1IntegralUserCrossRank.getValue(),
						new RelationActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(temp.getReward()),userInfo.getUnionUid(), activityInfo.getActivityId()));
				GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(temp.getUserId());
				if(gamePlayer != null){
					gamePlayer.getModule(CurrencyModule.class).addCurrency(CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId()) + "=" + temp.getReward(), eLogMoneyType.CookBoy,eLogMoneyType.CrossCookBoyActivityOverMatch);
				}else{
					cookBoyData.setIntegral(cookBoyData.getIntegral() + temp.getReward());
				}
				cookBoyData.setAllIntegral(cookBoyData.getAllIntegral() + temp.getReward());
				updateMatchOverFood(temp.getUserId(),temp.getFinishFoodListList());
			}
		}
	}

	public void syncMatch(CookBoyProto.CrossCookBoyMatchSyncMsg msg){
		CookBoyProto.CookBoyPublicTableSyncMsg.Builder publicTableMsg = CookBoyProto.CookBoyPublicTableSyncMsg.newBuilder();
		publicTableMsg.addAllTableList(msg.getPublicTableList());
		List<Long> notOnlineUserId = new ArrayList<>();
		List<Long> userList = getSceneUser(0);
		for(long userId : userList){
			GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
			if(gamePlayer != null){
				gamePlayer.sendPacket(Protocol.U_COOK_BOY_SERVE_TABLE_SYNC, publicTableMsg);
			}else{
				notOnlineUserId.add(userId);
			}
		}
		for(long userId : notOnlineUserId){
			userList.remove(userId);
		}
	}

	public void reAddIntegral(GamePlayer player,int itemId){
		Object locker = getLock(player.getUserId());
		synchronized (locker){
			int integralItemId = CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId());
			if(itemId == integralItemId){
				CookBoyData cookBoyData = cookBoyDataMap.get(player.getUserId());
				if(cookBoyData.getIntegral() > 0){
					player.getModule(CurrencyModule.class).addCurrency(integralItemId + "=" + cookBoyData.getIntegral(), eLogMoneyType.CookBoy,eLogMoneyType.CrossCookBoyActivityLogin);
					cookBoyData.setIntegral(0);
					synchronized (needUpdateCookBoyList){
						if(!needUpdateCookBoyList.contains(cookBoyData)){
							needUpdateCookBoyList.add(cookBoyData);
						}
					}
				}
			}
		}
	}

	public void clearIntegral(GamePlayer player,int itemId){
		Object locker = getLock(player.getUserId());
		synchronized (locker){
			int integralItemId = CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId());
			if(itemId == integralItemId){
				UserBagItem userBagItem = player.getModule(BagModule.class).getUserBagItem(integralItemId);
				if(userBagItem != null){
					player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(integralItemId + "=" + userBagItem.getNum()), eLogMoneyType.CookBoy,eLogMoneyType.CrossCookBoyActivityNewAc);
				}
			}
		}
	}

	public void updateMatchOverFood(long userId,List<CookBoyProto.CookBoyFinishFoodTempMsg> list){
		List<LogCookBoy1MatchFood> logList = new ArrayList<>();
		CookBoyData cookBoyData = cookBoyDataMap.get(userId);
		Map<Integer,CookBoyFinishFood> finishMap = cookBoyData.getFinishFoodMap();
		for(CookBoyProto.CookBoyFinishFoodTempMsg tempMsg : list){
			for(CookBoyFinishFood cookBoyFinishFood : finishMap.values()){
				if(tempMsg.getId() == cookBoyFinishFood.getIndex()){
					cookBoyFinishFood.setStatus(eCookBoyFoodStatusType.IsOver.getValue());
					cookBoyFinishFood.setRank(tempMsg.getRank());
					cookBoyFinishFood.setNo(tempMsg.getNo());
					LogCookBoy1MatchFood log = new LogCookBoy1MatchFood(activityInfo.getActivityId(),userId,cookBoyFinishFood.getNo(),cookBoyFinishFood.getFoodId(),cookBoyFinishFood.getRank(),cookBoyFinishFood.getFraction());
					logList.add(log);
					break;
				}
			}
		}
		cookBoyData.setFinishFoodMap(finishMap);
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(player != null){
			player.getModule(CookBoyModule.class).syncSelfTable(activityInfo.getActivityId());
		}
		synchronized (needUpdateCookBoyList){
			if(!needUpdateCookBoyList.contains(cookBoyData)){
				needUpdateCookBoyList.add(cookBoyData);
			}
		}
		for (LogCookBoy1MatchFood logCookBoy1MatchFood : logList) {
			AutoLogMgr.add(logCookBoy1MatchFood);
		}
	}

	public MakeFoodRes makeFood(long userId,int times){
		MakeFoodRes res = new MakeFoodRes();
		CookBoyData cookBoyData = cookBoyDataMap.get(userId);
		if(!cookBoyData.isAble() || cookBoyData.getNo() != eActivityCookBoyType.Process1.getChildType()){
			res.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
			return res;
		}
		recoveryMakeFoodHp(cookBoyData);
		if(cookBoyData.getHp() - times < 0){
			res.setRet(GameErrorCode.E_COOK_BOY_MAKE_FOOD_NO_HP);
			return res;
		}

		Map<Integer,CookBoyFood> foodMap = cookBoyData.getTableFoodMap();
		//次数大于剩余的空位置是修正到满
		int emptyCount = getEmptyTableCount(foodMap);
		if(emptyCount == 0){
			res.setRet(GameErrorCode.E_COOK_BOY_TABLE_FOOD_FULL);
			return res;
		}
		if(times > emptyCount){
			times = emptyCount;
		}
		//体力不用
        cookBoyData.setHp(cookBoyData.getHp() - times);
		for(int i = 1; i <= GameConfig.COOK_BOY_TABLE_MAX_POSITION; i++){
			CookBoyFood tempFood = foodMap.get(i);
			if(tempFood.getLevel() == 0){
				makeOneFood(tempFood,activityInfo.getActivityId());
				res.addCookBoyFood(tempFood);
				if(--times == 0){
					break;
				}
			}
		}
		cookBoyData.setTableFoodMap(foodMap);
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(player != null){
			player.getModule(CookBoyModule.class).syncSelfTable(activityInfo.getActivityId());
		}
		synchronized (needUpdateCookBoyList){
			if(!needUpdateCookBoyList.contains(cookBoyData)){
				needUpdateCookBoyList.add(cookBoyData);
			}
		}

		//日志
		Map<Integer,LogCookBoy1MakeFood> logMap = new ConcurrentHashMap<>();
		for(CookBoyFood cookBoyFood : res.getMakeList()){
			if(!logMap.containsKey(cookBoyFood.getLevel())){
				logMap.put(cookBoyFood.getLevel(), new LogCookBoy1MakeFood(cookBoyData.getActivityId(), cookBoyData.getUserId(), 0, cookBoyFood.getLevel(), 0));
			}
			LogCookBoy1MakeFood log = logMap.get(cookBoyFood.getLevel());
			log.setCost(log.getCost() + 1);
			log.setNum(log.getNum() + 1);
		}
		List<LogCookBoy1MakeFood> logCookBoy1MakeFoodsList = new ArrayList<>(logMap.values());
		for (LogCookBoy1MakeFood logCookBoy1MakeFood : logCookBoy1MakeFoodsList) {
			AutoLogMgr.add(logCookBoy1MakeFood);
		}

		return res;
	}

	//使用体力同步体力的时候
	public void recoveryMakeFoodHp(CookBoyData cookBoyData){
		int recoveryTime = CookBoyActivityMgr.getCookBoyRecoveryTime(cookBoyData.getActivityId());
		int maxHp = CookBoyActivityMgr.getCookBoyMaxHp(cookBoyData.getActivityId());
		int hp = cookBoyData.getHp();
		long hpTime = cookBoyData.getHpTime();
		long passTime = System.currentTimeMillis() - hpTime;
		long recoveryValue = passTime/(recoveryTime*1000);
		if(hp >= maxHp){
			cookBoyData.setHp(hp);
		}else if(hp + recoveryValue < maxHp){
			cookBoyData.setHp(hp + (int)recoveryValue);
		}else if(hp + recoveryValue >= maxHp){
			cookBoyData.setHp(maxHp);
		}
		if(cookBoyData.getHp() >= maxHp){
			cookBoyData.setHpTime(System.currentTimeMillis());
		}else{
			cookBoyData.setHpTime(hpTime + recoveryValue * recoveryTime * 1000);
		}
		synchronized (needUpdateCookBoyList){
			if(!needUpdateCookBoyList.contains(cookBoyData)){
				needUpdateCookBoyList.add(cookBoyData);
			}
		}
	}

	private void makeOneFood(CookBoyFood cookBoyFood,int activityId){
		int level = CookBoyActivityMgr.randomOneFoodLevel(activityId);
		Map<Integer,Integer> scoreMap = CookBoyActivityMgr.getMakeFoodScoreMap(activityId);
		cookBoyFood.setLevel(level);
		cookBoyFood.setFraction(scoreMap.get(level));
	}

	private int getEmptyTableCount(Map<Integer,CookBoyFood> foodMap){
		int count = 0;
		for(int i = 1; i <= GameConfig.COOK_BOY_TABLE_MAX_POSITION; i++){
			CookBoyFood tempFood = foodMap.get(i);
			if(tempFood.getLevel() == 0){
				count++;
			}
		}
		return count;
	}

	//合成菜品两个以上就能合成
	public CookBoyFinishFood foodMerge(long userId){
		Map<Integer,LogCookBoy1MergeFood> levelLogMap = new ConcurrentHashMap<>();
		CookBoyFinishFood newCookBoyFinishFood = null;
		Object locker = getLock(userId);
		long addIntegral = 0;
		synchronized (locker){
			CookBoyData cookBoyData = cookBoyDataMap.get(userId);
			if(cookBoyData == null){
				return null;
			}
			Map<Integer,CookBoyFood> foodMap = cookBoyData.getTableFoodMap();
			Map<Integer,CookBoyFinishFood> finishFoodMap = cookBoyData.getFinishFoodMap();
			//菜没有切满,最后一个地方没有菜
			if(foodMap.get(foodMap.size()).getLevel() == 0){
				return null;
			}
			Map<Integer,List<CookBoyFood>> levelMap = new ConcurrentHashMap<>();
			for(int level = 1; level <= GameConfig.COOK_BOY_FOOD_MAX_LEVEL;level++){
				levelMap.put(level,new ArrayList<>());
			}
			for(int pos = 1; pos <= GameConfig.COOK_BOY_TABLE_MAX_POSITION; pos++){
				CookBoyFood tempFood = foodMap.get(pos);
				if(tempFood.getLevel() == 0){
					break;
				}
				levelMap.get(tempFood.getLevel()).add(tempFood);
			}

			for(int level = 1; level <= GameConfig.COOK_BOY_FOOD_MAX_LEVEL;level++){
				List<CookBoyFood> cookBoyFoodList = levelMap.get(level);
				if(cookBoyFoodList.size() <= 1)continue;
				long allScore = 0;
				int combe = cookBoyFoodList.size() - 1;
				int mulValue;
				if(combe > 1){
					mulValue = CookBoyActivityMgr.getMergeFoodCombe(activityInfo.getActivityId(),level,combe);
				}else{
					mulValue = 1000;
				}
				for(CookBoyFood cookBoyFood : cookBoyFoodList){
					allScore += cookBoyFood.getFraction();
				}
				levelMap.put(level,new ArrayList<>());
				//等级大于合成菜变成成品菜
				if(level + 1 > GameConfig.COOK_BOY_FOOD_MAX_LEVEL){
					newCookBoyFinishFood = new CookBoyFinishFood();
					int addScore = CookBoyActivityMgr.getCookBoyFinishFoodAddScore(activityInfo.getActivityId(),cookBoyData.getFinishFoodId());
					newCookBoyFinishFood.setFoodId(cookBoyData.getFinishFoodId());
					newCookBoyFinishFood.setIndex(finishFoodMap.size()+1);
					newCookBoyFinishFood.setFraction((int)((allScore * mulValue * (1000 + addScore)) / (1000 * 1000)));
					newCookBoyFinishFood.setNo(0);
					newCookBoyFinishFood.setRank(0);
					newCookBoyFinishFood.setTime(System.currentTimeMillis());
					newCookBoyFinishFood.setStatus(eCookBoyFoodStatusType.NoServe.getValue());
					newCookBoyFinishFood.setLevel(level + 1);
					newCookBoyFinishFood.makeProcess(cookBoyFoodList);
					finishFoodMap.put(finishFoodMap.size()+1,newCookBoyFinishFood);
					int finishFoodId = CookBoyActivityMgr.getMakeFinishFoodId(activityInfo.getActivityId(),cookBoyData.getFinishFoodId(),finishFoodMap);
					cookBoyData.setFinishFoodId(finishFoodId);
					cookBoyData.setFinishFoodMap(finishFoodMap);
					addIntegral += newCookBoyFinishFood.getFraction();
					RelationActivityMgr.conditionNotify(activityInfo.getActivityId(),userId, eGamePlayerEventType.CookBoy1MakeFoodFinishCount.getValue(),finishFoodMap.size());
					levelLogMap.put(level,new LogCookBoy1MergeFood(activityInfo.getActivityId(),userId,level,level+1,combe+1,combe,newCookBoyFinishFood.getFraction()));
				}else{
					CookBoyFood newCookBoyFood = new CookBoyFood();
					newCookBoyFood.setLevel(level + 1);
					newCookBoyFood.setFraction((int)(allScore * mulValue / 1000));
					newCookBoyFood.makeProcess(cookBoyFoodList);
					levelMap.get(level+1).add(newCookBoyFood);
					addIntegral += newCookBoyFood.getFraction();
					levelLogMap.put(level,new LogCookBoy1MergeFood(activityInfo.getActivityId(),userId,level,level+1,combe+1,combe,newCookBoyFood.getFraction()));
				}
			}
			Map<Integer,CookBoyFood> newTable = initCookBoyFood();
			for(int level = 1; level <= GameConfig.COOK_BOY_FOOD_MAX_LEVEL;level++) {
				List<CookBoyFood> cookBoyFoodList = levelMap.get(level);
				for(CookBoyFood cookBoyFood : cookBoyFoodList){
					setOneFood(newTable,cookBoyFood);
				}
			}
			cookBoyData.setTableFoodMap(newTable);
			GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
			UserInfo userInfo = UserMgr.getUserInfo(userId);
			RelationActivityMgr.conditionNotify(activityInfo.getActivityId(),userId, eGamePlayerEventType.CookBoy1IntegralUserCrossRank.getValue(),
					new RelationActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(addIntegral),userInfo.getUnionUid(), activityInfo.getActivityId()));
			// 积分是道具要加上去 会并发要加锁
			cookBoyData.setAllIntegral(cookBoyData.getAllIntegral() + addIntegral);
			if(player != null){
				player.getModule(CurrencyModule.class).addCurrency(CookBoyActivityMgr.getCookBoyIntegralItemId(activityInfo.getActivityId()) + "=" + addIntegral, eLogMoneyType.CookBoy,eLogMoneyType.CrossCookBoyActivityMergeFood);
			}else{
				//不在线加到临时地方，上线加上去
				cookBoyData.setIntegral(cookBoyData.getIntegral() + addIntegral);
			}
			if(player != null){
				player.getModule(CookBoyModule.class).syncSelfTable(activityInfo.getActivityId());
			}
			synchronized (needUpdateCookBoyList){
				if(!needUpdateCookBoyList.contains(cookBoyData)){
					needUpdateCookBoyList.add(cookBoyData);
				}
			}
		}
		List<LogCookBoy1MergeFood> logCookBoy1MergeFoodsList = new ArrayList<>(levelLogMap.values());
		for (LogCookBoy1MergeFood logCookBoy1MergeFood : logCookBoy1MergeFoodsList) {
			AutoLogMgr.add(logCookBoy1MergeFood);
		}

		CookBoyProto.CookBoyMergeFoodRespMsg.Builder respMsg = CookBoyProto.CookBoyMergeFoodRespMsg.newBuilder();
		respMsg.setRet(0);
		respMsg.setScore(addIntegral);
		if(newCookBoyFinishFood != null){
			CookBoyProto.CookBoyFinishFoodTempMsg.Builder finishTemp = CookBoyProto.CookBoyFinishFoodTempMsg.newBuilder();
			finishTemp.setId(newCookBoyFinishFood.getIndex());
			finishTemp.setFoodId(newCookBoyFinishFood.getFoodId());
			finishTemp.setFraction(newCookBoyFinishFood.getFraction());
			finishTemp.setStatus(newCookBoyFinishFood.getStatus());
			finishTemp.setNo(newCookBoyFinishFood.getNo());
			finishTemp.setRank(newCookBoyFinishFood.getRank());
			finishTemp.setTime((int)(newCookBoyFinishFood.getTime()/1000));
			respMsg.setFinishFood(finishTemp);
		}
		GamePlayerMgr.getPlayer(userId).sendPacket(Protocol.U_COOK_BOY_MERGE_FOOD, respMsg);
		return newCookBoyFinishFood;
	}

	private void setOneFood(Map<Integer,CookBoyFood> foodTable,CookBoyFood cookBoyFood){
		for(CookBoyFood temp : foodTable.values()){
			if(temp.getLevel() == 0){
				temp.setLevel(cookBoyFood.getLevel());
				temp.setFraction(cookBoyFood.getFraction());
				temp.setProcess(cookBoyFood.getProcess());
				break;
			}
		}
	}


	//参赛成功记录
	public CookBoyData serveFoodRespond(long userId,int no,int index){
		CookBoyData cookBoyData = cookBoyDataMap.get(userId);
		Map<Integer, CookBoyFinishFood> cookBoyFinishFoodMap = cookBoyData.getFinishFoodMap();
		for (CookBoyFinishFood cookBoyFinishFood : cookBoyFinishFoodMap.values()){
			if(cookBoyFinishFood.getIndex() == index && cookBoyFinishFood.getStatus() == eCookBoyFoodStatusType.NoServe.getValue()){
				cookBoyFinishFood.setNo(no);
				//若果结束直接传结束状态
				cookBoyFinishFood.setStatus(eCookBoyFoodStatusType.OnTable.getValue());
			}
		}
		cookBoyData.setFinishFoodMap(cookBoyFinishFoodMap);
		synchronized (needUpdateCookBoyList){
			if(!needUpdateCookBoyList.contains(cookBoyData)){
				needUpdateCookBoyList.add(cookBoyData);
			}
		}
		return cookBoyData;
	}

	private CookBoyData initCookBoy1(long userId){
		CookBoyData temp = new CookBoyData();
		temp.setActivityId(activityInfo.getActivityId());
		temp.setUserId(userId);
		temp.setNo(activityInfo.getChildType());
		temp.setAble(true);
		temp.setIntegral(0);
		temp.setAllIntegral(0);
		temp.setHp(CookBoyActivityMgr.getCookBoyHp(activityInfo.getActivityId()));
		temp.setHpTime(System.currentTimeMillis());
		temp.setFinishFoodId(CookBoyActivityMgr.getDefaultCookingId(activityInfo.getActivityId()));
		temp.setTableFoodMap(initCookBoyFood());
		temp.setFinishFoodCount(0);
		temp.setFinishFoodData("{}");
		temp.setDishId(1);
		temp.setProcess(0);
		temp.setDishCount(0);
		synchronized (needAddCookBoyList){
			if(!needAddCookBoyList.contains(temp)){
				needAddCookBoyList.add(temp);
			}
		}
		return temp;
	}
	private Map<Integer, CookBoyFood> initCookBoyFood(){
		Map<Integer,CookBoyFood> cookBoyFoodMap = new ConcurrentHashMap<>();
		for(int i = 1; i <= GameConfig.COOK_BOY_TABLE_MAX_POSITION; i++){
			CookBoyFood temp = new CookBoyFood();
			temp.setPos(i);
			temp.setLevel(0);
			temp.setFraction(0);
			temp.setProcess("");
			cookBoyFoodMap.put(temp.getPos(),temp);
		}
		return cookBoyFoodMap;
	}

	public boolean init() {
		return reload();
	}

	public boolean stop() {
		return false;
	}

	public boolean save() {
		List<CookBoyData> tempAddList;
		synchronized (needAddCookBoyList) {
			tempAddList = new ArrayList<>(needAddCookBoyList);
			needAddCookBoyList.clear();
		}
		if (tempAddList.size() > 0) {
			UserCookBoyBussiness.addUserCooBoyList(tempAddList);
		}
		//保存记录
		List<CookBoyData> tempUpdataList;
		synchronized (needUpdateCookBoyList) {
			tempUpdataList = new ArrayList<>(needUpdateCookBoyList);
			needUpdateCookBoyList.clear();
		}
		if (tempUpdataList.size() > 0) {
			UserCookBoyBussiness.updateUserCookBoyList(tempUpdataList);
		}
		return true;
	}

	public ActivityInfo getActivityInfo(){
		return activityInfo;
	}

	public boolean reload() {
		cookBoyDataMap = UserCookBoyBussiness.getUserCookBoyMap(activityInfo.getActivityId());
		return true;
	}

	public boolean isUserCookBoyAble(long userId) {

		if(cookBoyDataMap.containsKey(userId)){
			return cookBoyDataMap.get(userId).isAble();
		}
		return false;
	}
}
